from rest_framework import status
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet

from taunt.cjz_serializers import SpitModelSerializer
from taunt.taunt_serializers import SpitUitSerializer
from users.models import Spit, User
# 获取吐槽评论
class  SpitCommentView(ModelViewSet):
    queryset = Spit.objects.all()
    serializer_class = SpitModelSerializer

    def retrieve(self, request, *args, **kwargs):
        spits = Spit.objects.filter(parent_id=id)
        # instance = self.get_object()
        serializer = self.serializer_class(instance=spits, many=True)
        return Response(serializer.data)



class SpitViewSet(ModelViewSet):
    queryset = Spit.objects.all()
    # queryset = Spit.objects.filter(parent=None).all()
    serializer_class = SpitModelSerializer

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(Spit.objects.filter(parent=None))

        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)

    def create(self, request, *args, **kwargs):

        if request.data.get('parent'):
            # 为评论行为
            if not request.user.is_authenticated:
                return Response({
                    'message': '请您登录后操作',
                    'success': False
                })

            request.data['userid'] = request.user.id

            bs = self.get_serializer(data=request.data)
            bs.is_valid(raise_exception=True)
            self.perform_create(bs)
            spit = Spit.objects.get(id=request.data.get('parent'))
            spit.comment += 1
            spit.save()
            headers = self.get_success_headers(bs.data)
            return Response(bs.data, status=status.HTTP_201_CREATED, headers=headers)

        bs = self.get_serializer(data=request.data)
        bs.is_valid(raise_exception=True)
        self.perform_create(bs)
        # spit = bs.save()
        headers = self.get_success_headers(bs.data)
        return Response(bs.data, status=status.HTTP_201_CREATED, headers=headers)

    def retrieve(self, request, *args, **kwargs):
        pk = self.kwargs.get('pk')
        queryset = self.get_queryset().filter(parent=pk)

        # 吐槽详情
        spit = self.get_object()
        # spit = Spit.objects.get(id=pk)
        spit.visits += 1
        spit.save()
        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)

    def perform_authentication(self, request):
        pass
    #
    #
    # def GetComment(self, request, id):
    #
    #     spits = Spit.objects.filter(parent_id=id)
    #     # instance = self.get_object()
    #     serializer = self.serializer_class(instance=spits, many=True)
    #     return Response(serializer.data)
